#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

// Windows和Unix/Linux环境兼容处理
#ifdef _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #pragma comment(lib, "ws2_32.lib")
    
    // 替换Unix函数为Windows对应函数
    #define close(s) closesocket(s)
    typedef SOCKET socket_t;
    typedef int ssize_t;
    
    // Windows下的错误处理宏
    #define SOCKET_ERROR_CODE() WSAGetLastError()
#else
    #include <unistd.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <fcntl.h>
    typedef int socket_t;
    #define SOCKET_ERROR_CODE() errno
#endif

#define PORT 8080
#define BUFFER_SIZE 1024
#define MAX_CONNECTIONS 10

// 函数声明
void handle_request(socket_t client_socket);
void send_response(socket_t client_socket, const char *status_code, const char *content_type, const char *body);
void send_file(socket_t client_socket, const char *path);
char* get_file_extension(const char *filename);
char* get_content_type(const char *extension);

int main() {
    socket_t server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    
    // Windows环境下初始化Winsock
    #ifdef _WIN32
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("WSAStartup failed: %d\n", WSAGetLastError());
        return 1;
    }
    #endif
    
    // 创建套接字文件描述符
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("socket failed: %d\n", SOCKET_ERROR_CODE());
        #ifdef _WIN32
        WSACleanup();
        #endif
        exit(EXIT_FAILURE);
    }
    
    // 设置套接字选项以允许端口重用
    #ifdef _WIN32
    // Windows下只支持SO_REUSEADDR
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, 
                  (char*)&opt, sizeof(opt)) == SOCKET_ERROR) {
        printf("setsockopt failed: %d\n", SOCKET_ERROR_CODE());
    }
    #else
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, 
                  (void*)&opt, sizeof(opt)) != 0) {
        perror("setsockopt");
    }
    #endif
    
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY; // 监听所有网络接口
    address.sin_port = htons(PORT);
    
    // 绑定套接字到指定端口
    if (bind(server_fd, (struct sockaddr *)&address, 
                                 sizeof(address)) == SOCKET_ERROR) {
        printf("bind failed: %d\n", SOCKET_ERROR_CODE());
        close(server_fd);
        #ifdef _WIN32
        WSACleanup();
        #endif
        exit(EXIT_FAILURE);
    }
    
    // 开始监听连接
    if (listen(server_fd, MAX_CONNECTIONS) == SOCKET_ERROR) {
        printf("listen failed: %d\n", SOCKET_ERROR_CODE());
        close(server_fd);
        #ifdef _WIN32
        WSACleanup();
        #endif
        exit(EXIT_FAILURE);
    }
    
    printf("Web服务器启动，监听端口 %d...\n", PORT);
    
    // 主循环，接受连接
    while (1) {
        printf("等待连接...\n");
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, 
                       (socklen_t*)&addrlen)) == INVALID_SOCKET) {
            printf("accept failed: %d\n", SOCKET_ERROR_CODE());
            continue; // 发生错误时继续等待下一个连接，而不是退出
        }
        
        // 获取客户端IP地址（Windows和Unix/Linux通用）
        char client_ip[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &(address.sin_addr), client_ip, INET_ADDRSTRLEN);
        printf("客户端连接成功！IP地址: %s\n", client_ip);
        
        // 处理请求
        handle_request(new_socket);
        
        // 关闭连接
        close(new_socket);
        printf("连接已关闭\n");
    }
    
    // 实际上不会执行到这里，因为上面的循环是无限的
    close(server_fd);
    #ifdef _WIN32
    WSACleanup();
    #endif
    return 0;
}

void handle_request(socket_t client_socket) {
    char buffer[BUFFER_SIZE] = {0};
    
    // 读取客户端请求
    ssize_t bytes_read;
    #ifdef _WIN32
    bytes_read = recv(client_socket, buffer, BUFFER_SIZE, 0);
    #else
    bytes_read = read(client_socket, buffer, BUFFER_SIZE);
    #endif
    
    if (bytes_read < 0) {
        printf("Read failed: %d\n", SOCKET_ERROR_CODE());
        return;
    }
    
    // 客户端关闭连接
    if (bytes_read == 0) {
        return;
    }
    
    // 解析HTTP请求行
    char method[10], path[100], protocol[20];
    if (sscanf(buffer, "%s %s %s", method, path, protocol) != 3) {
        send_response(client_socket, "400 Bad Request", "text/plain", "Invalid request format");
        return;
    }
    
    printf("请求方法: %s\n请求路径: %s\nHTTP协议: %s\n", method, path, protocol);
    
    // 仅支持GET方法
    if (strcmp(method, "GET") != 0) {
        send_response(client_socket, "501 Not Implemented", "text/plain", "Method not implemented");
        return;
    }
    
    // 安全检查：防止目录遍历攻击
    if (strstr(path, "..") != NULL || strchr(path, '\\') != NULL) {
        send_response(client_socket, "403 Forbidden", "text/plain", "Access denied: Security restriction");
        return;
    }
    
    // 处理根路径，使用更优雅的方式
    if (strcmp(path, "/") == 0) {
        strcpy(path, "/index.html");
    }
    
    // 尝试发送请求的文件
    send_file(client_socket, path + 1); // 移除开头的'/'
}

void send_response(socket_t client_socket, const char *status_code, const char *content_type, const char *body) {
    char response[BUFFER_SIZE * 2];
    int body_len = strlen(body);
    
    // 构建HTTP响应
    sprintf(response, "HTTP/1.1 %s\r\n"  
                     "Content-Type: %s\r\n"  
                     "Content-Length: %d\r\n"  
                     "Connection: close\r\n"  
                     "\r\n"  
                     "%s", 
                     status_code, content_type, body_len, body);
    
    // 获取响应长度
    size_t response_len = strlen(response);
    
    // 发送响应，适配Windows环境
    #ifdef _WIN32
    if (send(client_socket, response, (int)response_len, 0) == SOCKET_ERROR) {
        printf("Send response failed: %d\n", SOCKET_ERROR_CODE());
    }
    #else
    if (write(client_socket, response, response_len) < 0) {
        perror("Write response failed");
    }
    #endif
}

void send_file(socket_t client_socket, const char *path) {
    FILE *file;
    struct stat file_stat;
    char response[BUFFER_SIZE];
    char buffer[BUFFER_SIZE];
    size_t bytes_read, bytes_written;
    long long file_size = 0;
    
    printf("尝试发送文件: %s\n", path);
    
    // 尝试打开文件
    file = fopen(path, "rb");
    if (file == NULL) {
        printf("文件不存在: %s\n", path);
        // 文件不存在，发送404响应
        send_response(client_socket, "404 Not Found", "text/html", "<html><body><h1>404 Not Found</h1><p>The requested resource was not found on this server.</p></body></html>");
        return;
    }
    
    // 获取文件大小
    if (fstat(fileno(file), &file_stat) < 0) {
        // 如果fstat失败，尝试通过其他方式获取文件大小
        fseek(file, 0, SEEK_END);
        file_size = ftell(file);
        fseek(file, 0, SEEK_SET);
        
        if (file_size < 0) {
            #ifdef _WIN32
            printf("获取文件大小失败: %d\n", SOCKET_ERROR_CODE());
            #else
            perror("获取文件大小失败");
            #endif
            fclose(file);
            send_response(client_socket, "500 Internal Server Error", "text/plain", "Server error");
            return;
        }
    } else {
        file_size = file_stat.st_size;
    }
    
    // 安全检查：限制文件大小
    if (file_size > 10 * 1024 * 1024) { // 10MB限制
        fclose(file);
        send_response(client_socket, "413 Payload Too Large", "text/plain", "File too large");
        return;
    }
    
    // 获取文件扩展名以确定内容类型
    char *extension = get_file_extension(path);
    char *content_type = get_content_type(extension);
    
    // 发送HTTP响应头
    sprintf(response, "HTTP/1.1 200 OK\r\n"  
                     "Content-Type: %s\r\n"  
                     "Content-Length: %lld\r\n"  
                     "Connection: close\r\n"  
                     "\r\n", 
                     content_type, file_size);
    
    // 发送响应头
    #ifdef _WIN32
    if (send(client_socket, response, (int)strlen(response), 0) == SOCKET_ERROR) {
        printf("发送响应头失败: %d\n", SOCKET_ERROR_CODE());
        fclose(file);
        return;
    }
    #else
    if (write(client_socket, response, strlen(response)) < 0) {
        perror("发送响应头失败");
        fclose(file);
        return;
    }
    #endif
    
    // 分块发送文件内容
    while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) > 0) {
        #ifdef _WIN32
        bytes_written = send(client_socket, buffer, (int)bytes_read, 0);
        #else
        bytes_written = write(client_socket, buffer, bytes_read);
        #endif
        
        if (bytes_written != (ssize_t)bytes_read) {
            #ifdef _WIN32
            printf("发送文件内容失败: %d\n", SOCKET_ERROR_CODE());
            #else
            perror("发送文件内容失败");
            #endif
            break;
        }
    }
    
    fclose(file);
    printf("文件发送完成: %s\n", path);
}

char* get_file_extension(const char *filename) {
    char *dot = strrchr(filename, '.');
    if (!dot || dot == filename) {
        return "";
    }
    return dot + 1;
}

char* get_content_type(const char *extension) {
    if (strcmp(extension, "html") == 0 || strcmp(extension, "htm") == 0) {
        return "text/html";
    } else if (strcmp(extension, "css") == 0) {
        return "text/css";
    } else if (strcmp(extension, "js") == 0) {
        return "application/javascript";
    } else if (strcmp(extension, "jpg") == 0 || strcmp(extension, "jpeg") == 0) {
        return "image/jpeg";
    } else if (strcmp(extension, "png") == 0) {
        return "image/png";
    } else if (strcmp(extension, "gif") == 0) {
        return "image/gif";
    } else if (strcmp(extension, "txt") == 0) {
        return "text/plain";
    } else {
        return "application/octet-stream";
    }
}